package de.grosjohann.android.feuerwehr.webservice;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;

public class FMSWsClient
  extends WsClient {

  FMSWsClient(String newUri, int connectionTimeout, int socketTimeout) throws ClientProtocolException, IOException {
    super(newUri, connectionTimeout, socketTimeout);
  }

  String post(String authorization, NameValuePair... params) throws ClientProtocolException, IOException, HttpException {
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setHeader("Accept", FMSWsClient.MEDIA_TYPE);
    httpPost.setHeader("Authorization", authorization);

    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.addAll(Arrays.asList(params));
    httpPost.setEntity(new UrlEncodedFormEntity(postParams));

    HttpResponse resp = hc.execute(httpPost);

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      return EntityUtils.toString(resp.getEntity());
    }

    throw new HttpException(resp.getStatusLine().getStatusCode() + "");
  }

}
